
type deviceT = {
    label: string;
    id: string;
    groupId: string;
};

// 权限查询列表
const permissionsNames = [
    "geolocation", // 定位
    "notifications", // 通知
    "push", // 推送
    "midi", // 设备接口
    "camera", // 摄像机
    "microphone", // 麦克风
    "speaker", // 扬声器
    "device-info", // 设备信息
    "background-fetch", //
    "background-sync", //
    "bluetooth", // 蓝牙
    "persistent-storage", // 长久存储
    "ambient-light-sensor", // 环境光传感器
    "accelerometer", // 加速计
    "gyroscope", // 陀螺仪
    "magnetometer", // 地磁仪
    "clipboard", // 剪贴板
    "display-capture", // 显示捕获
    "nfc", //
];

// 获取设备列表
export async function getDevicesList() {
    let micList: Array<deviceT> = []; //麦克风
    let cameraList: Array<deviceT> = []; //摄像头
    let speakerList: Array<deviceT> = []; //扬声器
    let defaultSpeaker: deviceT = {
        label: "默认",
        id: "default",
        groupId: "",
    };
    await navigator.mediaDevices
        .enumerateDevices()
        .then((list) => {
            if (!list)
                return {
                    micList,
                    cameraList,
                    speakerList,
                };
            // 赋与默认扬声器
            defaultSpeaker.groupId = list[2]?.groupId || "default";
            // 蓝牙麦克风统计-去除无效蓝牙麦克风
            let micLanyaList = list.filter((item) => {
                return item.kind === "audioinput" && item.label.includes("(Bluetooth)");
            });
            list.forEach((item) => {
                const camerastr = JSON.stringify(cameraList);
                const micstr = JSON.stringify(micList);
                const speakerstr = JSON.stringify(speakerList);

                // 摄像头-条件,不为空且不重复
                let camTerm_1 = camerastr == "[]" ? true : !camerastr.includes(item.groupId);
                // 麦克风-条件
                let micTerm_1 = item.label.indexOf("立体声混音") === -1;
                let micTerm_2 = micstr == "[]" ? true : !micstr.includes(item.groupId);
                let micTerm_3 = !(micLanyaList.length === 2 && item.label.includes("(Bluetooth)"));
                // 扬声器-条件
                let speakerTerm_1 = speakerstr == "[]" ? true : !speakerstr.includes(item.groupId);
                let term_1 = item.deviceId === ""; //通用过滤
                if (term_1) return false;
                let params = {
                    label: item.label,
                    id: item.deviceId,
                    groupId: item.groupId,
                };
                switch (item.kind) {
                    case "videoinput": //摄像头
                        if (camTerm_1) cameraList.push(params);
                        break;
                    case "audioinput": //麦克风
                        if (micTerm_1 && micTerm_2 && micTerm_3) micList.push(params);
                        break;
                    case "audiooutput": //扬声器
                        if (speakerTerm_1) speakerList.push(params);
                        break;
                    default:
                }
            });
        })
        .catch((err) => {
            console.log(err);
        });
    // 赋与默认扬声器
    if (speakerList.length === 0) {
        speakerList.push(defaultSpeaker);
    }

    return {
        micList: micList,
        cameraList: cameraList,
        speakerList: speakerList,
    };
}

// safari 浏览器判断
export const isSafari = () => {
    let term_1 = navigator.userAgent.indexOf("Safari") > 0;
    let term_2 = navigator.userAgent.indexOf("Chrome") < 0;
    return term_1 && term_2;
};
// 获取设备授权-浏览器兼容
const getUserMedia = async (constrains, success, error) => {
    if (navigator.mediaDevices.getUserMedia) {
        // 最新标准API
        return await navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
    } else if ((navigator as any).webkitGetUserMedia) {
        // webkit内核浏览器
        return await (navigator as any).webkitGetUserMedia(constrains).then(success).catch(error);
    } else if ((navigator as any).mozGetUserMedia) {
        // Firefox浏览器
        return await (navigator as any).mozGetUserMedia(constrains).then(success).catch(error);
    } else if ((navigator as any).getUserMedia) {
        // 旧版API
        return await (navigator as any).getUserMedia(constrains).then(success).catch(error);
    }
};
// 获取设备授权-成功的回调函数
const success = (stream) => {
    return stream;
};

// 获取设备授权-异常的回调函数
const error = (error) => {
    console.log(error);
    return false;
};
// 获取设备授权
export async function getUserMediaFn(
    parmas = {
        video: true,
        audio: true,
    }
) {
    let stream = false;
    let status = 0;
    // 0禁用 1成功 2询问 3不支持
    if ((navigator as any).mediaDevices.getUserMedia || (navigator as any).getUserMedia || (navigator as any).webkitGetUserMedia || (navigator as any).mozGetUserMedia) {
        // 调用用户媒体设备，访问摄像头
        stream = await getUserMedia(parmas, success, error);
        status = stream === false ? 0 : 1;
    } else {
        status = 3;
    }

    try {
        if (stream) (stream as any).getTracks().forEach((track) => track?.stop());
    } catch (error) {
        console.log(error);
    }
    return status;
}
// 获取浏览器版本信息
export function browserVersion() {
    try {
        const agent = navigator.userAgent.toLowerCase();
        let Browser = "";
        let Bversion = "";
        let verinNum: string = "";
        // IE

        if (agent.indexOf("msie") > 0) {
            const regStr_ie = /msie [\d.]+;/gi;

            Browser = "IE";
            Bversion = `${agent.match(regStr_ie)}`;
        }
        // firefox
        else if (agent.indexOf("firefox") > 0) {
            const regStr_ff = /firefox\/[\d.]+/gi;

            Browser = "firefox";
            Bversion = `${agent.match(regStr_ff)}`;
        }
        // Chrome
        else if (agent.indexOf("chrome") > 0) {
            const regStr_chrome = /chrome\/[\d.]+/gi;

            Browser = "chrome";
            Bversion = `${agent.match(regStr_chrome)}`;
        }
        // Safari
        else if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
            const regStr_saf = /version\/[\d.]+/gi;

            Browser = "safari";
            Bversion = `${agent.match(regStr_saf)}`;
        }
        // Opera
        else if (agent.indexOf("opera") >= 0) {
            const regStr_opera = /version\/[\d.]+/gi;

            Browser = "opera";
            Bversion = `${agent.match(regStr_opera)}`;
        } else if (agent.indexOf("messenger") >= 0) {
            const regStr_opera = /version\/[\d.]+/gi;
            Browser = "micro messenger";
            Bversion = `${agent.match(regStr_opera)}`;
        }
        let index = Bversion.indexOf("/");
        verinNum = index < 0 ? "90" : Bversion.substring(index + 1, Bversion.length);

        return [Browser, verinNum];
    } catch (error) {
        return [10, "浏览器检测失败"];
    }
}

// 全屏切换
export function triggerScreenFn() {
    try {
        let availHeight = window.screen.availHeight;
        let screenHeight = window.screen.height;
        if (availHeight === screenHeight) {
            const elem: any = parent.document;
            elem.webkitCancelFullScreen
                ? elem.webkitCancelFullScreen()
                : elem.mozCancelFullScreen
                ? elem.mozCancelFullScreen()
                : elem.cancelFullScreen
                ? elem.cancelFullScreen()
                : elem.msExitFullscreen
                ? elem.msExitFullscreen()
                : elem.exitFullscreen
                ? elem.exitFullscreen()
                : alert("切换失败,可尝试Esc退出");
        } else {
            const elem: any = document.body;
            elem.webkitRequestFullScreen
                ? elem.webkitRequestFullScreen()
                : elem.mozRequestFullScreen
                ? elem.mozRequestFullScreen()
                : elem.msRequestFullscreen
                ? elem.msRequestFullscreen()
                : elem.requestFullScreen
                ? elem.requestFullScreen()
                : alert("浏览器不支持全屏");
        }
    } catch (error) {
        console.log(error);
    }
}
// 拦截f11全屏
window.addEventListener("keydown", function (e) {
    e = e || window.event;
    if (e.key === "F11") {
        e.preventDefault();
        triggerScreenFn();
    }
});

// 权限查询
export async function permissionsQueryFn(name: any) {
    return new Promise<any>((resolve, reject) => {
        navigator?.permissions
            .query({
                name: name,
            })
            .then((permissionStatus) => {
                resolve(permissionStatus);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

// 元素选择器
(window as any).$ = function $(className: string) {
    if (!className || className == "") return null;
    let name = className.substring(1);
    switch (className[0]) {
        case ".":
            return document.getElementsByClassName(name);
        case "#":
            return document.getElementById(name);
        default:
            return document.getElementsByTagName(name);
    }
};

//复制
export function copyText(value: string) {
    navigator.clipboard.writeText(value);
}
